import React from "react"
import initNECaptcha from "./captcha"
import "./captcha.scss"

interface ICaptchaProps {
  captchaClose?: () => void
  callback?: (err: any, data: any) => void
  showCaptcha?: boolean
}

export class Captcha extends React.Component<ICaptchaProps, {}> {
  state = {
    captchaIns: null
  }

  componentDidMount(): void {
    initNECaptcha(
      {
        captchaId: "deca75ae543c43bdb495e9a551829591",
        element: "#captcha_div",
        mode: "popup",
        width: "320px",
        onClose: this.selfClose,
        onVerify: this.verify
      },
      (instance: any) => {
        this.setState({
          captchaIns: instance
        })
        // this.state.captchaIns = instance
      },
      (err: any) => {
        console.log(err)
      }
    )
  }

  componentDidUpdate(prevProps: any) {
    if (this.props.showCaptcha !== prevProps.showCaptcha && this.props.showCaptcha) {
      this.show()
    }
  }

  show = () => {
    // @ts-ignore
    this.state.captchaIns.refresh()
    // @ts-ignore
    this.state.captchaIns.popUp()
  }

  selfClose = () => {
    // @ts-ignore
    this.props.captchaClose()
  }

  // 让父组件自己验证
  verify = (err: any, data: any) => {
    // @ts-ignore
    this.props.callback(err, data)
  }

  render() {
    const { showCaptcha } = this.props
    return (
      <div className={showCaptcha ? "show-captcha" : "hide-captcha"}>
        <div className="captcha-wrap">
          <div className="captcha_div" id="captcha_div" ref="captchaInner"></div>
        </div>
      </div>
    )
  }
}
